﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace trunk.Views
{
    public partial class TcpIpListenerWindow : Window
    {
        private TcpListener _tcpListener;
        private Task _listeningTask;
        private bool _isListening;
        private List<ClientInfo> _clients = new List<ClientInfo>();

        public TcpIpListenerWindow()
        {
            InitializeComponent();
        }

        private async void StartListeningButton_Click(object sender, RoutedEventArgs e)
        {
            if (!_isListening)
            {
                try
                {
                    _tcpListener = new TcpListener(IPAddress.Any, 8888);
                    _tcpListener.Start();

                    _isListening = true;
                    _listeningTask = Task.Run(ListenForClients);

                    MessageBox.Show("开始监听连接。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"启动监听时出错: {ex.Message}");
                }
            }
        }

        private async Task ListenForClients()
        {
            while (_isListening)
            {
                try
                {
                    TcpClient client = await _tcpListener.AcceptTcpClientAsync();
                    var clientInfo = new ClientInfo { Client = client, Messages = new List<string>() };
                    _clients.Add(clientInfo);

                    Dispatcher.Invoke(() =>
                    {
                        ClientListBox.Items.Add(clientInfo);
                    });

                    await HandleClient(clientInfo);
                }
                catch (SocketException)
                {
                    break;
                }
            }
        }

        private async Task HandleClient(ClientInfo clientInfo)
        {
            try
            {
                NetworkStream stream = clientInfo.Client.GetStream();
                byte[] buffer = new byte[1024];
                while (clientInfo.Client.Connected)
                {
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        // 客户端断开连接
                        Dispatcher.Invoke(() =>
                        {
                            _clients.Remove(clientInfo);
                            ClientListBox.Items.Remove(clientInfo);
                        });
                        break;
                    }
                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Dispatcher.Invoke(() =>
                    {
                        clientInfo.Messages.Add(message);
                        ClientListBox.Items.Refresh();
                    });
                }
            }
            catch (Exception)
            {
                Dispatcher.Invoke(() =>
                {
                    _clients.Remove(clientInfo);
                    ClientListBox.Items.Remove(clientInfo);
                });
            }
        }

        private async void StopListeningButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isListening)
            {
                try
                {
                    _isListening = false;
                    _tcpListener.Stop();

                    if (_listeningTask != null)
                    {
                        await _listeningTask;
                    }

                    foreach (var client in _clients)
                    {
                        client.Client.Close();
                    }
                    _clients.Clear();
                    ClientListBox.Items.Clear();

                    MessageBox.Show("停止监听连接。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"停止监听时出错: {ex.Message}");
                }
            }
        }

        private void SendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button sendButton)
            {
                if (sendButton.DataContext is ClientInfo clientInfo)
                {
                    if (sendButton.Parent is StackPanel stackPanel)
                    {
                        if ((stackPanel.Parent as StackPanel).Children[1] is TextBox messageTextBox)
                        {
                            string message = messageTextBox.Text;
                            try
                            {
                                NetworkStream stream = clientInfo.Client.GetStream();
                                byte[] data = Encoding.UTF8.GetBytes(message);
                                stream.Write(data, 0, data.Length);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"发送消息时出错: {ex.Message}");
                            }
                        }
                    }
                }
            }
        }

        private void StopClientConnectionButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button stopButton)
            {
                if (stopButton.DataContext is ClientInfo clientInfo)
                {
                    try
                    {
                        clientInfo.Client.Close();
                        _clients.Remove(clientInfo);
                        ClientListBox.Items.Remove(clientInfo);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"停止客户端连接时出错: {ex.Message}");
                    }
                }
            }
        }
    }

    public class ClientInfo
    {
        public TcpClient Client { get; set; }
        public List<string> Messages { get; set; }
    }
}